package com.gitee.faster.webdav.logger;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.ClassUtil;
import com.gitee.faster.webdav.common.constant.Constants;
import com.gitee.faster.webdav.kernel.Configuration;
import org.slf4j.event.Level;

import java.io.File;
import java.util.Objects;

/**
 * @author hongda.li
 */
public class FileProcessor extends ConsoleProcessor {

    private static final String LOG_NAME = Configuration.getInstance().getLoggerPath()
            + "/%s"
            + Constants.LOG_SUFFIX;

    private static final String TEMPLATE = "%s [%-5s] [%-15s]%s%-45s: %s%n";

    /**
     * 当前日志对应的日期
     */
    private String logDate;

    /**
     * 日志追加写入对象
     */
    private FileWriter fileWriter;

    @Override
    public void process(String name, Level level, String message, Throwable throwable, Object[] args) {
        getFileWriter(DateUtil.today()).append(String.format(TEMPLATE,
                this.formatTime(),
                level.name(),
                this.currentThreadName(),
                Constants.DASH_SYMBOL,
                ClassUtil.getShortClassName(name),
                this.formatMessage(message, args)));
    }

    private FileWriter getFileWriter(String logDate) {
        if (!Objects.equals(this.logDate, logDate)) {
            this.logDate = logDate;
            this.fileWriter = new FileWriter(new File(String.format(LOG_NAME, this.logDate)));
        }
        return this.fileWriter;
    }
}
